
package cn.edu.scau.cmi.wangmaoren.comprehension.client;

import java.util.Iterator;
import java.util.List;

import org.springframework.context.ApplicationContext;

import af.javafx.layout.AfLinearLayout;
import cn.edu.scau.cmi.wangmaoren.comprehension.dao.StudentDAO;
import cn.edu.scau.cmi.wangmaoren.comprehension.dao.TeacherDAO;
import cn.edu.scau.cmi.wangmaoren.comprehension.domain.Student;
import cn.edu.scau.cmi.wangmaoren.comprehension.domain.Teacher;
import cn.edu.scau.cmi.wangmaoren.spring.util.ApplicationContextUtil;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.TreeTableColumn.CellDataFeatures;
import javafx.stage.Stage;
import javafx.util.Callback;

public class ComprehensionHibernateSpringClient extends Application
{
	private AfLinearLayout root = new AfLinearLayout();
	private AfLinearLayout leftPane = new AfLinearLayout();
	private AfLinearLayout rightPane = new AfLinearLayout();

	private Label topBlankLabel = new Label();
	private Label midBlankLabel = new Label();
	private Label bottomBlankLabel = new Label();

	private Button addStudentButton = new Button("添加学生信息");
	private Button alterStudentButton = new Button("修改学生信息");
	private Button deleteStudentButton = new Button("删除学生信息");

	private Button addTeacherButton = new Button("添加老师信息");
	private Button alterTeacherButton = new Button("修改老师信息");
	private Button deleteTeacherButton = new Button("删除老师信息");

	private TextField studentIdTextField = new TextField();
	private TextField studentNameTextField = new TextField();
	private TextField studentTidTextField = new TextField();
	private TextField studentOldIdTextField = new TextField();

	private TextField teacherIdTextField = new TextField();
	private TextField teacherNameTextField = new TextField();
	private TextField teacherSidTextField = new TextField();
	private TextField teacherOldIdTextField = new TextField();

	TreeTableView<Student> studentTable = new TreeTableView<Student>();
	TreeTableView<Teacher> teacherTable = new TreeTableView<Teacher>();

	ApplicationContext appclication = ApplicationContextUtil.getApplicationContext();
	private StudentDAO studentDAO = (StudentDAO) appclication.getBean("StudentDAO");
	private TeacherDAO teacherDAO = (TeacherDAO) appclication.getBean("TeacherDAO");

	@Override
	public void start(Stage primaryStage)
	{
		try
		{
			initLayout();// 初始化界面

			Scene scene = new Scene(root, 750, 850);
			primaryStage.setTitle("老师指导学生毕业设计");
			primaryStage.setScene(scene);
			primaryStage.show();

		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void main(String[] args)
	{
		launch(args);
	}

	public void openWindow()
	{
		initLayout();// 初始化界面

		Scene scene = new Scene(root, 750, 850);
		Stage stage = new Stage();
		stage.setTitle("老师指导学生毕业设计");
		stage.setScene(scene);
		stage.show();
	}

	private void addStudent()
	{
		if (!studentIdTextField.getText().isEmpty() && !studentNameTextField.getText().isEmpty())
		{
			Long id = Long.valueOf(studentIdTextField.getText().trim());
			String name = studentNameTextField.getText().trim();
			Teacher teacher = teacherDAO.findById(Long.valueOf(studentTidTextField.getText().trim()));

			Student student;

			if (teacher != null)
			{
				student = new Student(id, name, teacher);
			} else
			{
				student = new Student(id, name);
			}

			studentDAO.save(student);
		}
		teacherTable.getTreeItem(0).getChildren();
	}

	private void deleteStudent()
	{
		if (!studentOldIdTextField.getText().isEmpty())
		{
			Student student = studentDAO.findById(Long.valueOf(studentOldIdTextField.getText().trim()));
			studentDAO.delete(student);
		}
	}

	private void alterStudent()
	{
		if (!studentOldIdTextField.getText().isEmpty())
		{
			Student student = studentDAO.findById(Long.valueOf(studentOldIdTextField.getText().trim()));

			if (!studentIdTextField.getText().isEmpty())
			{
				student.setId(Long.valueOf(studentIdTextField.getText().trim()));
			}
			if (!studentNameTextField.getText().isEmpty())
			{
				student.setName(studentNameTextField.getText().trim());
			}
			if (!studentTidTextField.getText().isEmpty())
			{
				Teacher teacher = teacherDAO.findById(Long.valueOf(studentTidTextField.getText().trim()));
				student.setTeacher(teacher);
			}

			studentDAO.update(student);
		}
	}

	private void addTeacher()
	{
		if (!teacherIdTextField.getText().isEmpty() && !teacherNameTextField.getText().isEmpty())
		{
			Long id = Long.valueOf(teacherIdTextField.getText().trim());
			String name = teacherNameTextField.getText().trim();

			Teacher teacher;

			teacher = new Teacher(id, name);

			teacherDAO.save(teacher);
		}
	}

	private void deleteTeacher()
	{
		if (!teacherOldIdTextField.getText().isEmpty())
		{
			Teacher teacher = teacherDAO.findById(Long.valueOf(teacherOldIdTextField.getText().trim()));
			teacherDAO.delete(teacher);
		}
	}

	private void alterTeacher()
	{
		if (!teacherOldIdTextField.getText().isEmpty())
		{
			Teacher teacher = teacherDAO.findById(Long.valueOf(teacherOldIdTextField.getText().trim()));

			if (!teacherIdTextField.getText().isEmpty())
			{
				teacher.setId(Long.valueOf(teacherIdTextField.getText().trim()));
			}
			if (!teacherNameTextField.getText().isEmpty())
			{
				teacher.setName(teacherNameTextField.getText().trim());
			}

			teacherDAO.update(teacher);
		}
	}

	private void loadStudentData(List students)
	{
		TreeItem<Student> root = new TreeItem<Student>(new Student());
		studentTable.setRoot(root);
		studentTable.setShowRoot(false);

		Iterator<?> studentIterator = students.iterator();
		while (studentIterator.hasNext())
		{
			Student student = (Student) studentIterator.next();
			if (student.getTeacher() == null)
			{
				student.setTeacher(new Teacher());
			}
			root.getChildren().add(new TreeItem(student));
		}
	}

	private void loadTeacherData(List teachers)
	{
		TreeItem<Teacher> root = new TreeItem<Teacher>(new Teacher());
		teacherTable.setRoot(root);
		teacherTable.setShowRoot(false);

		Iterator<?> teacherIterator = teachers.iterator();
		while (teacherIterator.hasNext())
		{
			Teacher teacher = (Teacher) teacherIterator.next();
			root.getChildren().add(new TreeItem(teacher));
		}
	}

	/*
	 * 初始化界面
	 */
	private void initLayout()
	{
		initStudentTable();
		initTeacherTable();

		root.orientation(Orientation.HORIZONTAL).spacing(20).padding(20);
		root.getChildren().addAll(leftPane, rightPane);
		root.layout("3  2");

		leftPane.orientation(Orientation.VERTICAL).spacing(20).padding(20);
		leftPane.getChildren().addAll(studentTable, teacherTable);
		leftPane.layout("1  1");

		rightPane.orientation(Orientation.VERTICAL).spacing(20).padding(10);
		rightPane.getChildren().addAll(topBlankLabel, studentIdTextField, studentNameTextField, studentTidTextField,
				studentOldIdTextField, addStudentButton, alterStudentButton, deleteStudentButton, midBlankLabel,
				teacherIdTextField, teacherNameTextField, teacherSidTextField, teacherOldIdTextField, addTeacherButton,
				alterTeacherButton, deleteTeacherButton, bottomBlankLabel);
		rightPane.layout("20px  30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px");

		studentIdTextField.setPromptText("学生ID（添加/修改时有效）");
		studentNameTextField.setPromptText("学生姓名（添加/修改时有效）");
		studentTidTextField.setPromptText("导师ID（添加/修改时有效）");
		studentOldIdTextField.setPromptText("学生原始ID（修改/删除时有效）");

		teacherIdTextField.setPromptText("老师ID（添加/修改时有效）");
		teacherNameTextField.setPromptText("老师姓名（添加/修改时有效）");
		teacherSidTextField.setPromptText("学生ID(逗号相隔)(添加/修改时有效)");
		teacherOldIdTextField.setPromptText("老师原始ID（修改/删除时有效）");

		List<Student> students = studentDAO.findAll();
		loadStudentData(students);

		List<Teacher> teachers = teacherDAO.findAll();
		loadTeacherData(teachers);

		addStudentButton.setOnAction((e) -> {
			addStudent();
		});
		addTeacherButton.setOnAction((e) -> {
			addTeacher();
		});
		deleteStudentButton.setOnAction((e) -> {
			deleteStudent();
		});
		deleteTeacherButton.setOnAction((e) -> {
			deleteTeacher();
		});
		alterStudentButton.setOnAction((e) -> {
			alterStudent();
		});
		alterTeacherButton.setOnAction((e) -> {
			alterTeacher();
		});
	}

	private void initStudentTable()
	{
		// 添加多个列
		TreeTableColumn<Student, Student> columns[] = new TreeTableColumn[3];
		columns[0] = new TreeTableColumn("学生ID");
		columns[1] = new TreeTableColumn("学生姓名");
		columns[2] = new TreeTableColumn("导师ID");
		studentTable.getColumns().addAll(columns);

		// 定义每个列的列宽
		columns[0].setPrefWidth(123);
		columns[1].setPrefWidth(123);
		columns[2].setPrefWidth(123);

		// 设置 CellValueFactory (此段写法固定)
		Callback cellValueFactory = new Callback()
		{
			@Override
			public Object call(Object param)
			{
				CellDataFeatures p = (CellDataFeatures) param;
				return p.getValue().valueProperty();
			}
		};
		for (int i = 0; i < columns.length; i++)
		{
			columns[i].setCellValueFactory(cellValueFactory);
		}

		// 设置CellFactory，定义每一列的单元格的显示
		columns[0].setCellFactory((param) -> {
			return new StudentTableCell("id");
		});
		columns[1].setCellFactory((param) -> {
			return new StudentTableCell("name");
		});
		columns[2].setCellFactory((param) -> {
			return new StudentTableCell("teacher");
		});
	}

	private void initTeacherTable()
	{
		// 添加多个列
		TreeTableColumn<Teacher, Teacher> columns[] = new TreeTableColumn[2];
		columns[0] = new TreeTableColumn("老师ID");
		columns[1] = new TreeTableColumn("老师姓名");
		teacherTable.getColumns().addAll(columns);

		// 定义每个列的列宽
		columns[0].setPrefWidth(186);
		columns[1].setPrefWidth(186);

		// 设置 CellValueFactory (此段写法固定)
		Callback cellValueFactory = new Callback()
		{
			@Override
			public Object call(Object param)
			{
				CellDataFeatures p = (CellDataFeatures) param;
				return p.getValue().valueProperty();
			}
		};
		for (int i = 0; i < columns.length; i++)
		{
			columns[i].setCellValueFactory(cellValueFactory);
		}

		// 设置CellFactory，定义每一列的单元格的显示
		columns[0].setCellFactory((param) -> {
			return new TeacherTableCell("id");
		});
		columns[1].setCellFactory((param) -> {
			return new TeacherTableCell("name");
		});
	}

	// 学生单元格的显示
	class StudentTableCell extends TreeTableCell<Student, Student>
	{
		String columnID;

		public StudentTableCell(String columnID)
		{
			this.columnID = columnID;
		}

		@Override
		protected void updateItem(Student item, boolean empty)
		{
			super.updateItem(item, empty);

			if (empty || item == null)
			{
				setText(null);
				setGraphic(null);
			} else
			{
				setGraphic(null);
				if (columnID.equals("id"))
					this.setText(String.valueOf(item.getId()));
				else if (columnID.equals("name"))
					this.setText(String.valueOf(item.getName()));
				else if (columnID.equals("teacher"))
					this.setText(String.valueOf(item.getTeacher().getId()));
			}
		}

	}

	// 老师单元格的显示
	class TeacherTableCell extends TreeTableCell<Teacher, Teacher>
	{
		String columnID;

		public TeacherTableCell(String columnID)
		{
			this.columnID = columnID;
		}

		@Override
		protected void updateItem(Teacher item, boolean empty)
		{
			super.updateItem(item, empty);

			if (empty || item == null)
			{
				setText(null);
				setGraphic(null);
			} else
			{
				setGraphic(null);
				if (columnID.equals("id"))
					this.setText(String.valueOf(item.getId()));
				else if (columnID.equals("name"))
					this.setText(String.valueOf(item.getName()));
			}
		}
	}
}
